package com.zhiyou100.blog.aciton.user;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
/*
作者：苗天宝
班级：java37
班训：天道酬勤 不忘初衷
时间：2021年10月22日 上午11:56:19
*/
@WebServlet("/user/yzm")
public class UserYzmServlet extends HttpServlet {

	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String message="春夏秋冬上下左右男女老少大小多少于一二三四五六七八九张王李赵";
		//1 在内存中开辟空间 用于画画
		BufferedImage bin=new BufferedImage(150, 40, BufferedImage.TYPE_INT_RGB);
		//2 获取画笔
		Graphics2D g=(Graphics2D)bin.getGraphics();
		//3 涂染料 画背景
		g.setColor(Color.WHITE);
		//4 画背景:长方形
		g.fillRect(2, 2, 145, 35);
		//5 画主题
		//随机四五个字符
		String str="";
		for (int i = 0; i <4; i++) {
			  str+=message.charAt((int)(Math.random()*message.length()));
		}
		//给字符设置文字样式
		Font font=new Font(null, Font.BOLD, 30);
		g.setFont(font);
		//把字符串中的所有字符画到画布上
		for (int i = 0; i < str.length(); i++) {
			//笔蘸墨
			g.setColor(new Color((int)(Math.random()*100+120), (int)(Math.random()*100+120), (int)(Math.random()*100+120)));
			//写字
			g.drawString(str.charAt(i)+"", i*35+10, 30);
		}
		//画干扰线
		for (int i = 0; i < (int)(Math.random()*5+5); i++) {
			g.setColor(new Color((int)(Math.random()*50+120), (int)(Math.random()*50+120), (int)(Math.random()*50+120)));
			g.drawLine(2, (int)(Math.random()*35+2), 145, (int)(Math.random()*35+2));
		}
		//把验证码的信息装入session
		req.getSession().setAttribute("yzm", str);
		//把内存中图片的信息通过respionse的输出流 响应给客户端
		ImageIO.write(bin, "JPEG", resp.getOutputStream());
	}

	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}
}
